package com.murray.assignment.service.impl;

import com.murray.assignment.mapper.CartInfoMapper;
import com.murray.assignment.mapper.CartMapper;
import com.murray.assignment.mapper.SkuGoodsMapper;
import com.murray.assignment.pojo.Cart;
import com.murray.assignment.pojo.CartInfo;
import com.murray.assignment.pojo.SkuGoods;
import com.murray.assignment.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Murray
 * @Date 2021/8/4
 * @Time 9:54
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    CartInfoMapper cartInfoMapper;

    @Autowired
    CartMapper cartMapper;

    @Autowired
    SkuGoodsMapper skuGoodsMapper;

    @Override
    public Integer addGoodsToCart(CartInfo cartInfo) {
        //先查询购物车信息
        Integer integer = cartInfoMapper.CartInfoIsExist(cartInfo);
        //如果购物车中有对应的购物车
        //执行更新操作
        if (integer >= 1) {
            updateCartInfo(cartInfo);
        }
        //如果购物车信息中没有对应的信息
        //插入新的购物车信息
        if (integer <= 0) {
            insertCartInfo(cartInfo);
            cartMapper.updateCart(cartInfo.getCartId());
        }

        //返回购物车的中的商品数量

        return cartMapper.selectByCartId(cartInfo.getCartId());
    }

    @Override
    public Integer updateCartInfo(CartInfo cartInfo) {
        return cartInfoMapper.updateCartInfo(cartInfo);
    }

    @Override
    public Integer insertCartInfo(CartInfo cartInfo) {
        return cartInfoMapper.insertCartInfo(cartInfo);
    }

    @Override
    public Integer returnGoodsNums(Integer cartId) {
        return cartMapper.selectByCartId(cartId);
    }

    @Override
    public Cart selectCartDetails(Integer cartId) {

        //1.根据购物车id，查询该购物车中所有商品属性信息：sku_properties
        List<SkuGoods> skuGoodsList = skuGoodsMapper.selectSkuGoodsByCartId(cartId);
        //2.将该信息修改
        for (SkuGoods skuGoods : skuGoodsList) {
            String skuProperties = skuGoods.getSkuProperties();
            System.out.println("第一次=====" + skuProperties);
            skuProperties = skuProperties.replaceAll(",", "','");
            skuProperties = "'" + skuProperties + "'";
            System.out.println("拼装完成==========" + skuProperties);
            skuGoods.setSkuProperties(skuProperties);
        }
        //3.将cartId和sku商品属性信息传到mapper进行查询
        Map<String, Object> map = new HashMap<>();
        map.put("cartId", cartId);
        map.put("list", skuGoodsList);
        Cart cart = cartMapper.selectCartList(map);
        return cart;
    }

    @Override
    public Integer deleteGoodsFromCart(CartInfo cartInfo) {
        //1先删除
        cartInfoMapper.deleteGoodsFromCart(cartInfo);
        //2更新购物车中的商品总数
        cartMapper.subCart(cartInfo.getCartId());
        //3返回商品总数
        return cartMapper.selectByCartId(cartInfo.getCartId());
    }


}
